<template>

    <!-- 骨架屏动画 -->
    <el-skeleton :rows="13" v-if="loading"></el-skeleton>


    <!-- 文件列表 -->
    <div class="file-card" v-if="loading === false">
        <el-table 
            :data="fileList" 
            @row-click="handleClick"
            @selection-change="handleSelectionChange"
            empty-text="暂无文件"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="fileName" label="文件名" width="780" >
                <template #default="{ row }">
                    <!-- 新建行显示输入框与操作按钮 -->
                    <template v-if="row.isNew">
                        <el-input v-model="row.fileName" placeholder="输入文件夹名" />
                        <el-button size="small" @click="confirmNewFolder(row) " type="primary">√</el-button>
                        <el-button size="small" @click="cancelNewFolder(row)" type="danger">×</el-button>
                    </template>
                     <!-- 重命名行显示输入框（新增逻辑） -->
                    <template v-else-if="row.isRename">
                        <el-input v-model="row.fileName" placeholder="输入新名称" />
                        <el-button size="small" @click="confirmRename(row)" type="primary">√</el-button>
                        <el-button size="small" @click="cancelRename(row)" type="danger">×</el-button>
                    </template>
                    <!-- 普通行显示文件名 -->
                    <template v-else>
                        <Folder v-if="row.fileType === 3" />
                        <Image v-else-if="row.fileType===4" />
                        <Video v-else-if="row.fileType===5" />
                        <Document v-else-if="row.fileType===6" />
                        <Audio v-else-if="row.fileType===7" />
                        <Other v-else-if="row.fileType===8" />
                        <span class="file-name">{{ row.fileName }}</span>
                    </template>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="修改时间" width="200"    :formatter="formatTime"/>
            <el-table-column prop="fileSize" label="大小" :formatter="formatFileSize"/>
        </el-table>
    </div>

    <!-- 分页 -->
    <div>
        <el-pagination
            :current-page="currentPage"
            @current-change="handleCurrentChange"
            :page-size="pageSize"
            layout="prev, pager,    next"
            :total="total"
            style="margin-left: 700px; margin-top: 30px;"
        />
    </div>

    <!-- 预览弹窗 -->
    <Dialog/>
    
</template>

<script setup lang="ts"> 
import Folder from '@/components/icons/Folder.vue'
import Document from '@/components/icons/Document.vue'
import Image from '@/components/icons/Image.vue'
import Video from '@/components/icons/Video.vue'
import Audio from '@/components/icons/Audio.vue'
import Other from '@/components/icons/Other.vue'
import Dialog from '@/components/disk/preview/Dialog.vue'
import {fileStore} from '@/stores/disk/file'
import {computed,onMounted} from 'vue'
import {previewFile,createNewFolder,renameFile} from '@/api/disk/file'
import { ElMessage } from 'element-plus'
const store= fileStore();
// 格式化时间戳（毫秒 → 日期字符串）
const formatTime = (row: any) => {
  const timestamp = row.createTime;
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 格式化文件大小（字节 → MB/KB/B）
const formatFileSize = (row:any) => {
  const sizeBytes = row.fileSize;
  if (sizeBytes === null || sizeBytes === 0) {
    return '';
  }
  const KB = 1024;
  const MB = KB * KB;
  const GB = MB * KB;

  if (sizeBytes >= GB) {
    return `${(sizeBytes / GB).toFixed(2)} GB`;
  } else if (sizeBytes >= MB) {
    return `${(sizeBytes / MB).toFixed(2)} MB`;
  } else if (sizeBytes >= KB) {
    return `${(sizeBytes / KB).toFixed(2)} KB`;
  } else {
    return `${sizeBytes} B`;
  }
};
// 骨架屏动画
const loading=computed(() => {
    return store.state.loading
})

//选择文件
const handleClick =async (row: any) => {
    //当创建文件夹的时候返回
    if(row.isNew===true){
        return
    }
    // 新增：阻止重命名状态下的点击事件
    if (row.isRename === true) {
        return;
    }
    const file = row;
    //更新点击的文件或者文件夹
    store.updateCurrentClickFile(file)
    const url= await previewFile(file);
    // store.updatePreviewUrl('')
    // 强制添加时间戳参数，避免浏览器缓存（重点！）
    // const uniqueUrl = `${url.data}?t=${Date.now()}`;  
    switch (row.fileType) {
        case 3:
            // 跳转文件夹
            store.updateFileList(file)
            //把文件名传给面包屑
            const bread={
                id:file.id,
                name:file.fileName,
                path:file.filePath
            }
            store.updateCurrentBread(bread)
            break;
        case 4:
            // 预览图片
            store.updateDialogVisible(true)
            store.updatePreviewUrl(url.data)
            break;
        case 5:
            // 预览视频
            store.updatePreviewUrl(url.data)
            store.updateDialogVisible(true)
            break;
        // case 6:
        //     // 预览文档
        //     break;
        // case 7:
        //     // 预览音频
        //     break;
        // case 8:
        //     // 预览其他
        //     break;
        default:
            ElMessage.error('暂不支持预览该类型文件');
            break;
    }
}
//按钮开关显示，以及选中文件
const handleSelectionChange = (val: any) => {
    //添加或清除删除列表
    store.updateDeleteList(val)
    //添加到选择的文件列表
    store.updateCurrentFiles(val)
    if (val.length > 0) {
        store.changeShowButton(true)
    }else{
        store.changeShowButton(false)
        
    } 
}
// 确认新建：调用接口创建文件夹
const confirmNewFolder = async (row: any) => {
    if (!row.fileName.trim()) {
        return alert('文件夹名不可为空');
    }
    try {
        // 调用接口
        const data={
            folderName: row.fileName,
            parentId: row.parentId,
        }
        await createNewFolder(data)
        if(store.state.currentClickFile===null){
            //是根路径
            store.initFileList()
        }else{
            //不是根路径
            store.updateFileList(store.state.currentClickFile)
        }
    } catch (error) {
        console.error('创建失败', error);
    }
};

// 取消新建：移除临时条目
const cancelNewFolder = (row: any) => {
    if(store.state.currentClickFile===null){
        //是根路径
        store.initFileList()
    }else{
        //不是根路径
        store.updateFileList(store.state.currentClickFile)
    }
};



//分页
const fileList = computed(() => {
    return store.state.fileList
})
const total=computed(() => {
    return store.state.total
})
const currentPage=computed(() => {
    return store.state.currentPage  
})
const pageSize=computed(() => {
    return store.state.pageSize
})
//页数改变
const handleCurrentChange = (val: number) => {
    if(store.state.currentFolderPaht==='/'){
        store.updateCurrentPage(val)
        store.initFileList()
    }else{
        store.updateCurrentPage(val)
        store.updateFileList(store.state.currentClickFile)
    }
    
}
onMounted(() => {
    store.initFileList() 
})

// 重命名：调用接口重命名文件
const confirmRename = async (row: any) => {
    if (!row.fileName.trim()) {
        return alert('文件名不可为空');
    }   
    await renameFile(row)
    if(store.state.currentClickFile===null){
        //是根路径
        store.initFileList()
    }else{
        //不是根路径
        store.updateFileList(store.state.currentClickFile)
    }
};
// 取消重命名：移除临时条目
const cancelRename = (row: any) => {
    if(store.state.currentClickFile===null){
        //是根路径
        store.initFileList()
    }else{
        //不是根路径
        store.updateFileList(store.state.currentClickFile)
    }
};


</script>

<style scoped lang="less">
.file-card{
    margin-top: 20px;
    overflow-x: hidden;
    overflow-y: auto;
    /deep/.el-table__row {
        &:hover {
            cursor: pointer; 
        }
    };
    .el-input{
        width: 30%;
    }
    .el-button{
        margin-left: 20px;
    }
}
.file-name {
    vertical-align: middle; 
    font-size: 14px;
    color: #303133;
}

</style>